<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="参展商名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入参展商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="展位" prop="position">
        <el-input
          v-model="queryParams.position"
          placeholder="请输入展位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="exhibitorsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="参展商名称" align="center" prop="name"/>
      <el-table-column label="参展商分类" align="center" prop="type">
        <template slot-scope="scope">{{ returnTName(scope.row.type) || '--' }}</template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address"/>
      <el-table-column label="展位" align="center" prop="position"/>
      <el-table-column label="排序" align="center" prop="sort"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleUpdate(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参展商对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="参展商名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入参展商名称"/>
        </el-form-item>
        <el-form-item label="分类" prop="name">
          <el-select v-model="form.type" placeholder="请选择分类">
            <el-option
              v-for="item in options3"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址"/>
          <el-button @click="getGPS" style="margin-top: 10px">获取坐标</el-button>

        </el-form-item>
        <el-form-item label="定位" prop="gps">
          <el-input v-model="form.gps" placeholder="请输入定位"/>
        </el-form-item>
        <el-form-item label="头像" prop="headerImg">
          <el-upload
            v-loading="loadingup"
            class="avatar-uploader"
            :action="uploadImgUrl"
            :show-file-list="false"
            :headers="headers"
            :limit="1"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="展位" prop="position">
          <el-input v-model="form.position" placeholder="请输入展位"/>
        </el-form-item>
        <el-form-item label="轮播图" prop="carouselChart">

          <el-upload
            :action="uploadImgUrl"
            list-type="picture-card"
            :headers="headers"
            :on-success="handleAvatarSuccess1"
            :file-list="fileList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情图" prop="infoImg">
          <!--          <el-input v-model="form.infoImg" type="textarea" placeholder="请输入内容"/>-->

          <el-upload
            :action="uploadImgUrl"
            list-type="picture-card"
            :headers="headers"
            :on-success="handleAvatarSuccess2"
            :file-list="fileList2"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove2">
            <i class="el-icon-plus"></i>
          </el-upload>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-dialog>

  </div>
</template>

<script>
import {listExhibitors, getExhibitors, delExhibitors, addExhibitors, updateExhibitors} from "@/api/business/exhibitors";
import {getToken} from "@/utils/auth";
import {committiyanban, getGpsByAddress} from "@/api/login";
import {listType} from "@/api/business/type";

export default {
  name: "Exhibitors",
  data() {
    return {
      options3: [],
      fileList2: [],
      fileList: [],
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      imageUrl: '',
      // 遮罩层
      loadingup: false,
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参展商表格数据
      exhibitorsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      queryParamst: {
        pageNum: 1,
        pageSize: null,
        name: null,
        sort: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        address: null,
        gps: null,
        headerImg: null,
        position: null,
        carouselChart: null,
        infoImg: null,
        type: null,
        gps0: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      dialogVisible: false,
      dialogImageUrl: '',
    };
  },
  created() {
    this.getList();
    this.getTList()
  },
  methods: {
    getTList() {
      listType(this.queryParamst).then(response => {
        this.options3 = response.rows;


      });
    },
    returnTName(n) {
      let a = []
      if (n) {
        a = this.options3.filter(v => v.id == n)
        if (a.length > 0) {
          let name = a[0].name
          return name
        }

      } else {
        return ''
      }
    },
    getGPS() {
      if (!this.form.address) {
        this.$message.warning('请填写详细地址')
        return
      }
      getGpsByAddress({address: this.form.address}).then(res => {
        console.log(res)
        // return
        this.form.gps = res.data.location.lng + ',' + res.data.location.lat
      })
    },
    handleRemove(file, fileList) {

      const f2=[]

      console.log(file, fileList);
      if (fileList.length > 0) {
        fileList.forEach(v=>{
          if(v.response){
            f2.push(v.response.url)
          }else{
            f2.push(v.url)
          }
        })
        this.form.carouselChart = f2.join(',')

      } else {
        this.form.carouselChart = ''

      }
    },
    handleRemove2(file, fileList) {

      const f3=[]

      console.log(file, fileList);
      if (fileList.length > 0) {
        fileList.forEach(v=>{
          if(v.response){
            f3.push(v.response.url)
          }else{
            f3.push(v.url)
          }
        })
        this.form.infoImg = f3.join(',')

      } else {
        this.form.infoImg = ''

      }

    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleAvatarSuccess(res, file, fileList) {
      console.log('res', res, fileList)
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.headerImg = res.url
      this.loadingup = false

    },
    handleAvatarSuccess1(res, file, fileList) {

      console.log(fileList)
      const f1=[]
      fileList.forEach(v=>{
        if(v.response){
          f1.push(v.response.url)
        }else{
          f1.push(v.url)
        }
      })
      this.form.carouselChart = f1.join(',')
      // this.imageUrl = URL.createObjectURL(file.raw);
      // this.form.headerImg = res.url
      // this.loadingup = false
      // this.form.carouselChart = fileList.map(v => v.response.url).join(',')
      // console.log('res1', this.form.carouselChart)


    },
    handleAvatarSuccess2(res, file, fileList) {
      console.log(fileList)
      const f1=[]
      fileList.forEach(v=>{
        if(v.response){
          f1.push(v.response.url)
        }else{
          f1.push(v.url)
        }
      })
      this.form.infoImg = f1.join(',')
      // this.imageUrl = URL.createObjectURL(file.raw);
      // this.form.headerImg = res.url
      // this.loadingup = false
      // this.form.infoImg = fileList.map(v => v.response.url).join(',')
      // console.log('res1', this.form.infoImg)


    },
    beforeAvatarUpload(file) {
      this.loadingup = true
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      // return isJPG && isLt2M;
      return isLt2M;
    },
    /** 查询参展商列表 */
    getList() {
      this.loading = true;
      listExhibitors(this.queryParams).then(response => {
        this.exhibitorsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        address: null,
        gps: null,
        sort:null,
        headerImg: null,
        position: null,
        carouselChart: null,
        infoImg: null,
        type: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.fileList = []
      this.fileList2 = []
      this.imageUrl = ''
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加参展商";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      listType(this.queryParamst).then(response => {
        this.options3 = response.rows;
      });
      getExhibitors(id).then(res => {
        this.form = res.data;
        this.form.type = res.data.type * 1
        this.imageUrl = this.form.headerImg
        console.log(this.form.carouselChart)
        if (this.form.carouselChart) {
          if (this.form.carouselChart.split(',').length > 0) {
            this.form.carouselChart.split(',').forEach(v => {
              this.fileList.push({
                name: v,
                url: v
              })
            })
          }
        }
        if (this.form.infoImg) {
          if (this.form.infoImg.split(',').length > 0) {
            this.form.infoImg.split(',').forEach(v => {
              this.fileList2.push({
                name: v,
                url: v
              })
            })
          }
        }


        this.open = true;
        this.title = "修改参展商";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateExhibitors(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExhibitors(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除参展商编号为"' + ids + '"的数据项？').then(function () {
        return delExhibitors(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mobile/exhibitors/export', {
        ...this.queryParams
      }, `exhibitors_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader /deep/ .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
